// index.js
// 引入封装好的请求数据的js文件
const util = require('../../request/index')
Page({
  data: {
    carouselList: [],
    goodsList: [],
    goodsTypeList: [],
    typeId: 0,
    isBarList: true
  },
  onLoad: {

  },
  // 生命周期函数--监听页面显示
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this.getCarouselList();
    this.getTypeList();
    this.getGoodsList();
  },
  async getCarouselList() {
    var carouselList = wx.getStorageSync('carouselList');
    if (carouselList) {
      this.setData({
        carouselList: carouselList
      })
    } else {
      util.request_get('/web/carousel/list').then((res) => {
        if (res.code === 200) {
          this.setData({
            carouselList: res.data
          })
          wx.setStorageSync('carouselList', res.data)
        }
      })
  
    }
  },
  async getTypeList() {
    var typeList = wx.getStorageSync('typeList');
    console.log(typeList);
    if (typeList) {
      this.setData({
        goodsTypeList: typeList
      })
    } else {
      util.request_get('/web/goods-type/list').then((res) => {
        if (res.code === 200) {
          this.setData({
            goodsTypeList: res.goodsTypes
          })
          wx.setStorageSync('typeList', res.goodsTypes)
        }
  
      })
    }

  },
  async getGoodsList() {
    var goodsList = wx.getStorageSync('goodsList-' + this.data.typeId);
    if (goodsList) {
      this.setData({
        goodsList: goodsList
      })
    } else {
      util.request_get('/web/index/goods/list', {
        goodsTypeId: this.data.typeId 
      }).then((res) => {
        if (res.code === 200) {
          this.setData({
            goodsList: res.data
          })
          wx.setStorageSync('goodsList-' + this.data.typeId, res.data)
        }
      })
    }
    
  },
  getGoodsListByTypeId(e) {
    let typeId = e.currentTarget.dataset.typeid;
    this.setData({
      typeId
    })
    this.getGoodsList()
  },
  viewGoodsDetails(e) {
    let carouselId = e.currentTarget.dataset.carouselid;
    wx.navigateTo({
      url: '/pages/goods-detail/goods-detail?carouselId=' + carouselId,
    })
  },
  getChangeBarList(e) {
    this.setData({
      isBarList: e.detail
    })
  }
})